#include "http_context.h"

#include <QDebug>

#include <sstream>

HttpContext::HttpContext()
    : m_state(HttpRequestDecodeState::kStart)
{

}

HttpContext::~HttpContext()
{
    qInfo() << "delete HttpContext............";
}

/**
 * @brief HttpContext::parseRequest 处理HTTP请求报文的解析
 * @param data HTTP报文数据
 */
void HttpContext::parseRequest(const QByteArray &data)
{
    m_request.tryDecode(data);
    m_state = m_request.getDecodeState();
}

/**
 * @brief HttpContext::reset 重置状态
 */
void HttpContext::reset()
{
    m_state = HttpRequestDecodeState::kStart;
    HttpRequest dummy;
    m_request = dummy;
}

/**
 * @brief HttpContext::debugPrintHttpMessage 调试打印http报文
 */
void HttpContext::debugPrintHttpMessage()
{
    std::stringstream strStream;
    // 打印方法名
    strStream << "method: " << m_request.getMethod().toStdString() << "\n";
    // 打印URL
    strStream << "url: " << m_request.getUrl().toStdString() << "\n";
    // 打印请求参数
    if (!m_request.getRequestParams().empty()) {
        strStream << "-------------------------[请求参数 BEGIN]------------" << "\n";

        for (const auto &key : m_request.getRequestParams().keys()) {
            strStream << key.toStdString() << " : " << m_request.getRequestParams()[key].toStdString() << "\n";
        }

        strStream << "-------------------------[请求参数 END]------------" << "\n";
    }

    // 打印HTTP协议
    strStream << "protocol: " << m_request.getProtocol().toStdString() << "\n";
    // 打印版本号
    strStream << "version: " << m_request.getVersion().toStdString() << "\n";

    // 打印HTTP请求头部字段
    for (const auto &key : m_request.getHeaders().keys()) {
        strStream << key.toStdString() << " : " << m_request.getHeaders()[key].toStdString() << "\n";
    }

    strStream.write(m_request.getBody().data(), static_cast<std::streamsize>(m_request.getBody().length()));
    strStream << "\n";

    qInfo() << qPrintable(QString::fromStdString(strStream.str()));
}
